using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;

namespace WpfRegexDesigner.Model
{
	public class RegexOptionsValueList : ObservableCollection<RegexOptionsValue>
	{
		/// <summary>
		/// Initializes a new instance of the RegexOptionsValueList class.
		/// </summary>
		/// <remarks>
		/// Excludes zero by default.
		/// </remarks>
		public RegexOptionsValueList()
			: this(ff => (ff != (int)RegexOptions.None && ff != (int)RegexOptions.Compiled))
		{
			XDocument xd = null;
			var fileName = "regexOptionsDescriptions.xml";
			try
			{
				xd = XDocument.Load(fileName);
			}
			catch (Exception ex)
			{
				foreach (var item in this)
				{
					item.Description = ex.ToString();
				}
				return;
			}
			foreach (RegexOptionsValue item in this)
			{
				var qry = from desc in xd.Descendants("descriptions").Descendants("description")
							 where (string.Compare(desc.Attribute("name").Value, item.Name, true) == 0)
							 select desc;

				var description = "Description not found.";
				if (qry != null)
				{
					var tehFirst = qry.FirstOrDefault();
					if (tehFirst != null)
					{
						description = tehFirst.Attribute("value").Value;
					}
				}
				item.Description = description;
			}
		}

		public RegexOptions Value
		{
			get
			{
				RegexOptions retVal = 0;
				foreach (var item in this)
				{
					if (item.IsSelected)
               {
						retVal |= item.Value;
					}
				}
				return retVal;
			}
		}

		/// <summary>
		/// Initializes a new instance of the RegexOptionsValueList class.
		/// </summary>
		/// <param name="filterFunction">
		/// A function that returns true for each candidate value that should be included in the collection.
		/// </param>
		public RegexOptionsValueList(Func<int, bool> filterFunction)
		{
			foreach (int item in Enum.GetValues(typeof(System.Text.RegularExpressions.RegexOptions)))
			{
				if (filterFunction(item))
				{
					this.Add(new RegexOptionsValue(item));
				}
			}
		}
	}
}
